import { Router } from "express";
import { authenticateWxAppToken } from "../middleware/wxapp-auth";
import { authenticateToken } from "../middleware/auth";
import { Appointment, HospitalSite, IHospitalSite } from "../models/mongodb-schemas";

const router = Router();

// 内存存储（生产环境应使用数据库）
interface Hospital {
  id: string;
  name: string;
  address: string;
  phone: string;
  level: string;
  city: string;
  distance?: number;
}

interface Department {
  id: string;
  hospitalId: string;
  name: string;
  description: string;
  doctorCount: number;
  availableSlots: number;
}

interface Doctor {
  id: string;
  departmentId: string;
  name: string;
  title: string;
  specialty: string;
  experience: string;
  avatar: string;
  rating: number;
  price: number;
}

interface TimeSlot {
  time: string;
  available: boolean;
  price: number;
  reason?: string;
}

interface AppointmentOrder {
  id: string;
  userId: string;
  hospitalId: string;
  hospitalName: string;
  departmentId: string;
  departmentName: string;
  doctorId: string;
  doctorName: string;
  appointmentDate: string;
  timeSlot: string;
  status: 'pending' | 'confirmed' | 'completed' | 'cancelled';
  price: number;
  queueNumber?: number;
  createTime: string;
  remark?: string; // 管理员备注
  patientInfo?: {
    name: string;
    phone: string;
    idCard?: string;
  };
}

// 辅助函数：将 HospitalSite 转换为 Hospital 格式
function convertHospitalSiteToHospital(site: IHospitalSite, userLat?: number, userLng?: number): Hospital {
  // 计算距离（如果提供用户坐标）
  let distance = 0;
  if (userLat && userLng) {
    const R = 6371; // 地球半径（公里）
    const dLat = (site.coordinates.latitude - userLat) * Math.PI / 180;
    const dLon = (site.coordinates.longitude - userLng) * Math.PI / 180;
    const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
              Math.cos(userLat * Math.PI / 180) * Math.cos(site.coordinates.latitude * Math.PI / 180) * 
              Math.sin(dLon/2) * Math.sin(dLon/2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    distance = R * c;
  }

  return {
    id: site.siteId,
    name: site.name,
    address: site.address,
    phone: site.contactInfo?.phone || "暂无电话",
    level: "三甲", // 默认等级，后续可以添加到 HospitalSite 模型中
    city: site.city || "未知城市",
    distance: Math.round(distance * 10) / 10 // 保留一位小数
  };
}

// Fallback 医院数据（当数据库无数据时使用）
const fallbackHospitals: Hospital[] = [
  {
    id: "h001",
    name: "河北省保定市莲池区保定市第一医院",
    address: "河北省保定市莲池区东风东路572号",
    phone: "0312-5976120",
    level: "三甲",
    city: "保定",
    distance: 0.5
  },
  {
    id: "h002", 
    name: "保定市人民医院",
    address: "保定市竞秀区长城北大街320号",
    phone: "0312-5976666",
    level: "三甲",
    city: "保定",
    distance: 1.2
  },
  {
    id: "h003",
    name: "保定市中医院",
    address: "保定市莲池区裕华东路530号", 
    phone: "0312-5976888",
    level: "三甲",
    city: "保定",
    distance: 2.1
  }
];

const departments: Department[] = [
  { id: "d001", hospitalId: "h001", name: "内科", description: "内科疾病诊治", doctorCount: 15, availableSlots: 20 },
  { id: "d002", hospitalId: "h001", name: "外科", description: "外科手术及治疗", doctorCount: 12, availableSlots: 15 },
  { id: "d003", hospitalId: "h001", name: "妇产科", description: "妇科及产科诊疗", doctorCount: 8, availableSlots: 18 },
  { id: "d004", hospitalId: "h001", name: "儿科", description: "儿童疾病诊疗", doctorCount: 10, availableSlots: 25 },
  { id: "d005", hospitalId: "h001", name: "心血管科", description: "心血管疾病专科", doctorCount: 6, availableSlots: 12 },
  { id: "d006", hospitalId: "h002", name: "内科", description: "内科疾病诊治", doctorCount: 18, availableSlots: 22 },
  { id: "d007", hospitalId: "h002", name: "骨科", description: "骨科疾病及创伤", doctorCount: 14, availableSlots: 16 },
  { id: "d008", hospitalId: "h003", name: "中医内科", description: "中医内科调理", doctorCount: 12, availableSlots: 30 }
];

// ID映射：将新的 siteId 映射到旧的 hospitalId（用于兼容现有科室和医生数据）
const HOSPITAL_ID_MAPPING: { [siteId: string]: string } = {
  // HospitalSite 数据库中的医院站点映射到预约系统中的医院ID
  'h001': 'h001', // 河北省保定市莲池区保定市第一医院
  'h002': 'h002', // 河北省保定市竞秀区保定市人民医院  
  'h003': 'h003', // 保定市中医院
};

// 辅助函数：获取兼容的 hospitalId
function getCompatibleHospitalId(siteId: string): string {
  // 首先检查是否是旧的ID格式
  if (siteId.startsWith('h0')) {
    return siteId;
  }
  
  // 检查映射表
  if (HOSPITAL_ID_MAPPING[siteId]) {
    return HOSPITAL_ID_MAPPING[siteId];
  }
  
  // 如果没有映射，返回默认值
  return 'h001'; // 默认使用第一个医院
}

const doctors: Doctor[] = [
  {
    id: "doc001",
    departmentId: "d001", 
    name: "张明华",
    title: "主任医师",
    specialty: "心血管内科",
    experience: "15年",
    avatar: "https://api.multiavatar.com/zhang.svg",
    rating: 4.8,
    price: 50
  },
  {
    id: "doc002",
    departmentId: "d001",
    name: "李晓红", 
    title: "副主任医师",
    specialty: "消化内科",
    experience: "12年",
    avatar: "https://api.multiavatar.com/li.svg",
    rating: 4.6,
    price: 40
  },
  {
    id: "doc003",
    departmentId: "d002",
    name: "王建军",
    title: "主任医师", 
    specialty: "普外科",
    experience: "18年",
    avatar: "https://api.multiavatar.com/wang.svg",
    rating: 4.9,
    price: 60
  },
  {
    id: "doc004",
    departmentId: "d003",
    name: "刘亚娟",
    title: "主治医师",
    specialty: "妇科",
    experience: "8年", 
    avatar: "https://api.multiavatar.com/liu.svg",
    rating: 4.5,
    price: 35
  },
  {
    id: "doc005",
    departmentId: "d004",
    name: "陈国伟",
    title: "副主任医师",
    specialty: "儿童呼吸科",
    experience: "10年",
    avatar: "https://api.multiavatar.com/chen.svg", 
    rating: 4.7,
    price: 45
  }
];

// 预约数据现在存储在MongoDB数据库中

// 生成时间段
function generateTimeSlots(date: string, doctorId: string): TimeSlot[] {
  const slots: TimeSlot[] = [];
  const today = new Date();
  const appointmentDate = new Date(date);
  
  // 上午时间段 (8:00-12:00)
  for (let hour = 8; hour < 12; hour++) {
    for (let min = 0; min < 60; min += 30) {
      const timeStr = `${hour.toString().padStart(2, '0')}:${min.toString().padStart(2, '0')}-${hour === 11 && min === 30 ? '12:00' : `${(min === 30 ? hour + 1 : hour).toString().padStart(2, '0')}:${min === 30 ? '00' : '30'}`}`;
      
      // 随机生成可用性（模拟真实情况）
      const isAvailable = Math.random() > 0.3; // 70%可用
      slots.push({
        time: timeStr,
        available: isAvailable,
        price: 50,
        reason: isAvailable ? undefined : '已预约'
      });
    }
  }
  
  // 下午时间段 (14:00-17:30)
  for (let hour = 14; hour < 18; hour++) {
    for (let min = 0; min < 60; min += 30) {
      if (hour === 17 && min === 30) break; // 17:30结束
      
      const timeStr = `${hour.toString().padStart(2, '0')}:${min.toString().padStart(2, '0')}-${min === 30 ? (hour + 1).toString().padStart(2, '0') + ':00' : hour.toString().padStart(2, '0') + ':30'}`;
      
      const isAvailable = Math.random() > 0.4; // 60%可用
      slots.push({
        time: timeStr,
        available: isAvailable,
        price: 50,
        reason: isAvailable ? undefined : '已预约'
      });
    }
  }
  
  return slots;
}

// 获取医院列表（从 HospitalSite 数据库获取）
router.get("/hospitals", async (req, res) => {
  try {
    const { city = "保定", page = "1", limit = "50", q, lat, lng } = req.query;
    
    // 构建查询条件
    const filter: any = { 
      status: 'active' // 只显示激活的医院站点
    };
    
    if (city) {
      filter.city = city;
    }
    
    // 搜索过滤
    if (q) {
      const query = q.toString();
      filter.$or = [
        { name: { $regex: query, $options: 'i' } },
        { address: { $regex: query, $options: 'i' } }
      ];
    }
    
    const pageNum = parseInt(page.toString());
    const pageSize = parseInt(limit.toString());
    const skip = (pageNum - 1) * pageSize;
    
    // 获取用户坐标（用于计算距离）
    const userLat = lat ? parseFloat(lat.toString()) : undefined;
    const userLng = lng ? parseFloat(lng.toString()) : undefined;
    
    try {
      // 从 HospitalSite 数据库获取医院数据
      const [hospitalSites, total] = await Promise.all([
        HospitalSite.find(filter)
          .sort({ createdAt: -1 })
          .skip(skip)
          .limit(pageSize)
          .lean(),
        HospitalSite.countDocuments(filter)
      ]);
      
      // 转换数据格式
      const hospitals = hospitalSites.map(site => 
        convertHospitalSiteToHospital(site, userLat, userLng)
      );
      
      // 按距离排序（如果提供了用户位置）
      if (userLat && userLng) {
        hospitals.sort((a, b) => (a.distance || 0) - (b.distance || 0));
      }
      
      res.json({
        success: true,
        data: {
          hospitals,
          total,
          page: pageNum,
          limit: pageSize
        }
      });
      
    } catch (dbError) {
      console.warn("从数据库获取医院数据失败，使用 fallback 数据:", dbError);
      
      // 如果数据库查询失败，使用 fallback 数据
      let filteredHospitals = fallbackHospitals.filter(h => h.city === city);
      
      // 搜索过滤
      if (q) {
        const query = q.toString().toLowerCase();
        filteredHospitals = filteredHospitals.filter(h => 
          h.name.toLowerCase().includes(query) ||
          h.address.toLowerCase().includes(query)
        );
      }
      
      const offset = (pageNum - 1) * pageSize;
      const paginatedHospitals = filteredHospitals.slice(offset, offset + pageSize);
      
      res.json({
        success: true,
        data: {
          hospitals: paginatedHospitals,
          total: filteredHospitals.length,
          page: pageNum,
          limit: pageSize
        },
        message: "使用本地数据"
      });
    }
    
  } catch (error) {
    console.error("获取医院列表失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 获取科室列表
router.get("/departments", (req, res) => {
  try {
    const { hospitalId } = req.query;
    
    if (!hospitalId) {
      return res.status(400).json({
        success: false,
        message: "医院ID为必填项"
      });
    }
    
    // 获取兼容的医院ID（支持从HospitalSite API获取的ID）
    const compatibleHospitalId = getCompatibleHospitalId(hospitalId.toString());
    const hospitalDepartments = departments.filter(d => d.hospitalId === compatibleHospitalId);
    
    res.json({
      success: true,
      data: {
        departments: hospitalDepartments,
        hospitalId: hospitalId.toString(),
        compatibleHospitalId
      }
    });
  } catch (error) {
    console.error("获取科室列表失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 获取医生列表
router.get("/doctors", (req, res) => {
  try {
    const { departmentId, date } = req.query;
    
    if (!departmentId) {
      return res.status(400).json({
        success: false,
        message: "科室ID为必填项"
      });
    }
    
    const departmentDoctors = doctors.filter(d => d.departmentId === departmentId);
    
    res.json({
      success: true,
      data: departmentDoctors
    });
  } catch (error) {
    console.error("获取医生列表失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 获取可预约时间段
router.get("/slots", (req, res) => {
  try {
    const { doctorId, date } = req.query;
    
    if (!doctorId || !date) {
      return res.status(400).json({
        success: false,
        message: "医生ID和日期为必填项"
      });
    }
    
    const timeSlots = generateTimeSlots(date.toString(), doctorId.toString());
    
    res.json({
      success: true,
      data: timeSlots
    });
  } catch (error) {
    console.error("获取时间段失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 创建预约订单
router.post("/orders", authenticateWxAppToken, async (req, res) => {
  try {
    const { hospitalId, hospitalName, departmentId, departmentName, doctorId, doctorName, appointmentDate, timeSlot, price, patientInfo } = req.body;
    const userId = req.user!.id;
    
    // 验证必要字段
    if (!hospitalId || !departmentId || !doctorId || !appointmentDate || !timeSlot) {
      return res.status(400).json({
        success: false,
        message: "预约信息不完整"
      });
    }
    
    // 生成订单ID
    const orderId = `apt_${Date.now()}_${userId.slice(-4)}`;
    
    // 创建预约记录
    const appointmentData = new Appointment({
      appointmentId: orderId,
      userId,
      hospitalId,
      hospitalName,
      departmentId, 
      departmentName,
      doctorId,
      doctorName,
      appointmentDate,
      timeSlot,
      status: 'confirmed',
      price: price || 50,
      queueNumber: Math.floor(Math.random() * 20) + 1,
      patientInfo
    });
    
    // 保存到数据库
    const savedAppointment = await appointmentData.save();
    
    console.log(`新预约订单已保存到数据库: ${doctorName} - ${appointmentDate} ${timeSlot} (用户: ${userId})`);
    
    // 转换为响应格式
    const appointment = {
      id: savedAppointment.appointmentId,
      userId: savedAppointment.userId,
      hospitalId: savedAppointment.hospitalId,
      hospitalName: savedAppointment.hospitalName,
      departmentId: savedAppointment.departmentId,
      departmentName: savedAppointment.departmentName,
      doctorId: savedAppointment.doctorId,
      doctorName: savedAppointment.doctorName,
      appointmentDate: savedAppointment.appointmentDate,
      timeSlot: savedAppointment.timeSlot,
      status: savedAppointment.status,
      price: savedAppointment.price,
      queueNumber: savedAppointment.queueNumber,
      createTime: savedAppointment.createdAt.toISOString(),
      patientInfo: savedAppointment.patientInfo,
      remark: savedAppointment.remark
    };
    
    res.json({
      success: true,
      message: "预约成功",
      data: {
        orderId,
        appointment
      }
    });
  } catch (error) {
    console.error("创建预约失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 获取我的预约列表
router.get("/orders", authenticateWxAppToken, async (req, res) => {
  try {
    const { status, page = "1", limit = "10" } = req.query;
    const userId = req.user!.id;
    
    // 构建查询条件
    const query: any = { userId };
    if (status && status !== 'all') {
      query.status = status;
    }
    
    // 分页参数
    const pageNum = parseInt(page.toString());
    const pageSize = parseInt(limit.toString());
    const skip = (pageNum - 1) * pageSize;
    
    // 从数据库查询预约
    const appointments = await Appointment.find(query)
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(pageSize)
      .lean();
    
    // 获取总数
    const total = await Appointment.countDocuments(query);
    
    // 转换为响应格式
    const userAppointments = appointments.map(apt => ({
      id: apt.appointmentId,
      userId: apt.userId,
      hospitalId: apt.hospitalId,
      hospitalName: apt.hospitalName,
      departmentId: apt.departmentId,
      departmentName: apt.departmentName,
      doctorId: apt.doctorId,
      doctorName: apt.doctorName,
      appointmentDate: apt.appointmentDate,
      timeSlot: apt.timeSlot,
      status: apt.status,
      price: apt.price,
      queueNumber: apt.queueNumber,
      createTime: apt.createdAt.toISOString(),
      patientInfo: apt.patientInfo,
      remark: apt.remark
    }));
    
    res.json({
      success: true,
      data: {
        appointments: userAppointments,
        total,
        page: pageNum,
        limit: pageSize
      }
    });
  } catch (error) {
    console.error("获取预约列表失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 取消预约
router.delete("/orders/:id", authenticateWxAppToken, async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user!.id;
    
    // 查找预约
    const appointment = await Appointment.findOne({ appointmentId: id });
    if (!appointment) {
      return res.status(404).json({
        success: false,
        message: "预约不存在"
      });
    }
    
    // 验证是否是本人的预约
    if (appointment.userId !== userId) {
      return res.status(403).json({
        success: false,
        message: "无权取消此预约"
      });
    }
    
    // 更新状态为已取消
    appointment.status = 'cancelled';
    appointment.updatedAt = new Date();
    await appointment.save();
    
    console.log(`预约已取消: ${id} (用户: ${userId})`);
    
    // 转换为响应格式
    const appointmentData = {
      id: appointment.appointmentId,
      userId: appointment.userId,
      hospitalId: appointment.hospitalId,
      hospitalName: appointment.hospitalName,
      departmentId: appointment.departmentId,
      departmentName: appointment.departmentName,
      doctorId: appointment.doctorId,
      doctorName: appointment.doctorName,
      appointmentDate: appointment.appointmentDate,
      timeSlot: appointment.timeSlot,
      status: appointment.status,
      price: appointment.price,
      queueNumber: appointment.queueNumber,
      createTime: appointment.createdAt.toISOString(),
      patientInfo: appointment.patientInfo,
      remark: appointment.remark
    };
    
    res.json({
      success: true,
      message: "预约已取消",
      data: appointmentData
    });
  } catch (error) {
    console.error("取消预约失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// ========== 管理员专用接口 ==========

// 获取所有预约（管理员权限）
router.get("/admin/orders", authenticateToken, async (req, res) => {
  try {
    const { status, hospitalId, departmentId, startDate, endDate, page = "1", limit = "20", search } = req.query;
    
    // 构建查询条件
    const query: any = {};
    
    // 状态过滤
    if (status && status !== 'all') {
      query.status = status;
    }
    
    // 医院过滤
    if (hospitalId && hospitalId !== 'all') {
      query.hospitalId = hospitalId;
    }
    
    // 科室过滤
    if (departmentId && departmentId !== 'all') {
      query.departmentId = departmentId;
    }
    
    // 日期范围过滤
    if (startDate || endDate) {
      query.appointmentDate = {};
      if (startDate) {
        query.appointmentDate.$gte = startDate;
      }
      if (endDate) {
        query.appointmentDate.$lte = endDate;
      }
    }
    
    // 搜索过滤（患者姓名或医生姓名）
    if (search) {
      const searchTerm = search.toString();
      query.$or = [
        { 'patientInfo.name': { $regex: searchTerm, $options: 'i' } },
        { doctorName: { $regex: searchTerm, $options: 'i' } },
        { hospitalName: { $regex: searchTerm, $options: 'i' } }
      ];
    }
    
    // 分页参数
    const pageNum = parseInt(page.toString());
    const pageSize = parseInt(limit.toString());
    const skip = (pageNum - 1) * pageSize;
    
    // 从数据库查询预约
    const appointments = await Appointment.find(query)
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(pageSize)
      .lean();
    
    // 获取总数
    const total = await Appointment.countDocuments(query);
    
    // 转换为响应格式
    const allAppointments = appointments.map(apt => ({
      id: apt.appointmentId,
      userId: apt.userId,
      hospitalId: apt.hospitalId,
      hospitalName: apt.hospitalName,
      departmentId: apt.departmentId,
      departmentName: apt.departmentName,
      doctorId: apt.doctorId,
      doctorName: apt.doctorName,
      appointmentDate: apt.appointmentDate,
      timeSlot: apt.timeSlot,
      status: apt.status,
      price: apt.price,
      queueNumber: apt.queueNumber,
      createTime: apt.createdAt.toISOString(),
      patientInfo: apt.patientInfo,
      remark: apt.remark
    }));
    
    res.json({
      success: true,
      data: {
        appointments: allAppointments,
        total,
        page: pageNum,
        limit: pageSize
      }
    });
  } catch (error) {
    console.error("获取预约列表失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 更新预约状态（管理员权限）
router.put("/admin/orders/:id/status", authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { status, remark } = req.body;
    
    // 查找预约
    const appointment = await Appointment.findOne({ appointmentId: id });
    if (!appointment) {
      return res.status(404).json({
        success: false,
        message: "预约不存在"
      });
    }
    
    // 验证状态值
    const validStatuses = ['pending', 'confirmed', 'completed', 'cancelled'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        message: "无效的状态值"
      });
    }
    
    // 更新状态
    appointment.status = status;
    if (remark) {
      appointment.remark = remark;
    }
    appointment.updatedAt = new Date();
    await appointment.save();
    
    console.log(`预约状态已更新: ${id} -> ${status}`);
    
    // 转换为响应格式
    const appointmentData = {
      id: appointment.appointmentId,
      userId: appointment.userId,
      hospitalId: appointment.hospitalId,
      hospitalName: appointment.hospitalName,
      departmentId: appointment.departmentId,
      departmentName: appointment.departmentName,
      doctorId: appointment.doctorId,
      doctorName: appointment.doctorName,
      appointmentDate: appointment.appointmentDate,
      timeSlot: appointment.timeSlot,
      status: appointment.status,
      price: appointment.price,
      queueNumber: appointment.queueNumber,
      createTime: appointment.createdAt.toISOString(),
      patientInfo: appointment.patientInfo,
      remark: appointment.remark
    };
    
    res.json({
      success: true,
      message: "预约状态更新成功",
      data: appointmentData
    });
  } catch (error) {
    console.error("更新预约状态失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 批量更新预约状态（管理员权限）
router.put("/admin/orders/batch-status", authenticateToken, async (req, res) => {
  try {
    const { appointmentIds, status, remark } = req.body;
    
    if (!Array.isArray(appointmentIds) || appointmentIds.length === 0) {
      return res.status(400).json({
        success: false,
        message: "预约ID列表不能为空"
      });
    }
    
    // 验证状态值
    const validStatuses = ['pending', 'confirmed', 'completed', 'cancelled'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        message: "无效的状态值"
      });
    }
    
    // 批量更新数据库
    const updateData: any = { 
      status, 
      updatedAt: new Date() 
    };
    if (remark) {
      updateData.remark = remark;
    }
    
    const updateResult = await Appointment.updateMany(
      { appointmentId: { $in: appointmentIds } },
      { $set: updateData }
    );
    
    // 获取更新后的预约记录
    const updatedAppointments = await Appointment.find({ 
      appointmentId: { $in: appointmentIds } 
    }).lean();
    
    // 找出未找到的ID
    const foundIds = updatedAppointments.map(apt => apt.appointmentId);
    const notFoundIds = appointmentIds.filter(id => !foundIds.includes(id));
    
    console.log(`批量更新预约状态: ${updateResult.modifiedCount}个成功, ${notFoundIds.length}个失败`);
    
    // 转换为响应格式
    const responseAppointments = updatedAppointments.map(apt => ({
      id: apt.appointmentId,
      userId: apt.userId,
      hospitalId: apt.hospitalId,
      hospitalName: apt.hospitalName,
      departmentId: apt.departmentId,
      departmentName: apt.departmentName,
      doctorId: apt.doctorId,
      doctorName: apt.doctorName,
      appointmentDate: apt.appointmentDate,
      timeSlot: apt.timeSlot,
      status: apt.status,
      price: apt.price,
      queueNumber: apt.queueNumber,
      createTime: apt.createdAt.toISOString(),
      patientInfo: apt.patientInfo,
      remark: apt.remark
    }));
    
    res.json({
      success: true,
      message: `成功更新${updateResult.modifiedCount}个预约状态`,
      data: {
        updated: responseAppointments,
        notFound: notFoundIds
      }
    });
  } catch (error) {
    console.error("批量更新预约状态失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 获取预约统计数据（管理员权限）
router.get("/admin/stats", authenticateToken, async (req, res) => {
  try {
    const { startDate, endDate, hospitalId } = req.query;
    
    // 构建查询条件
    const query: any = {};
    
    // 日期范围过滤
    if (startDate || endDate) {
      query.appointmentDate = {};
      if (startDate) {
        query.appointmentDate.$gte = startDate;
      }
      if (endDate) {
        query.appointmentDate.$lte = endDate;
      }
    }
    
    // 医院过滤
    if (hospitalId && hospitalId !== 'all') {
      query.hospitalId = hospitalId;
    }
    
    // 使用聚合管道计算统计数据
    const [overview] = await Appointment.aggregate([
      { $match: query },
      {
        $group: {
          _id: null,
          total: { $sum: 1 },
          pending: { $sum: { $cond: [{ $eq: ["$status", "pending"] }, 1, 0] } },
          confirmed: { $sum: { $cond: [{ $eq: ["$status", "confirmed"] }, 1, 0] } },
          completed: { $sum: { $cond: [{ $eq: ["$status", "completed"] }, 1, 0] } },
          cancelled: { $sum: { $cond: [{ $eq: ["$status", "cancelled"] }, 1, 0] } }
        }
      }
    ]);
    
    // 今日预约统计
    const today = new Date().toISOString().split('T')[0];
    const [todayStats] = await Appointment.aggregate([
      { 
        $match: { 
          ...query,
          appointmentDate: today
        }
      },
      {
        $group: {
          _id: null,
          todayAppointments: { $sum: 1 }
        }
      }
    ]);
    
    // 即将到来的预约
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    const tomorrowStr = tomorrow.toISOString().split('T')[0];
    
    const [upcomingStats] = await Appointment.aggregate([
      { 
        $match: { 
          ...query,
          appointmentDate: { $gte: tomorrowStr },
          status: { $ne: "cancelled" }
        }
      },
      {
        $group: {
          _id: null,
          upcomingAppointments: { $sum: 1 }
        }
      }
    ]);
    
    // 按医院统计
    const hospitalStats = await Appointment.aggregate([
      { $match: query },
      {
        $group: {
          _id: "$hospitalId",
          hospitalId: { $first: "$hospitalId" },
          hospitalName: { $first: "$hospitalName" },
          total: { $sum: 1 },
          pending: { $sum: { $cond: [{ $eq: ["$status", "pending"] }, 1, 0] } },
          confirmed: { $sum: { $cond: [{ $eq: ["$status", "confirmed"] }, 1, 0] } },
          completed: { $sum: { $cond: [{ $eq: ["$status", "completed"] }, 1, 0] } },
          cancelled: { $sum: { $cond: [{ $eq: ["$status", "cancelled"] }, 1, 0] } }
        }
      }
    ]);
    
    // 按日期统计（最近7天）
    const dateStats = [];
    for (let i = 6; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      const dateStr = date.toISOString().split('T')[0];
      
      const [dayStats] = await Appointment.aggregate([
        { 
          $match: { 
            ...query,
            appointmentDate: dateStr
          }
        },
        {
          $group: {
            _id: null,
            total: { $sum: 1 },
            pending: { $sum: { $cond: [{ $eq: ["$status", "pending"] }, 1, 0] } },
            confirmed: { $sum: { $cond: [{ $eq: ["$status", "confirmed"] }, 1, 0] } },
            completed: { $sum: { $cond: [{ $eq: ["$status", "completed"] }, 1, 0] } },
            cancelled: { $sum: { $cond: [{ $eq: ["$status", "cancelled"] }, 1, 0] } }
          }
        }
      ]);
      
      dateStats.push({
        date: dateStr,
        total: dayStats?.total || 0,
        pending: dayStats?.pending || 0,
        confirmed: dayStats?.confirmed || 0,
        completed: dayStats?.completed || 0,
        cancelled: dayStats?.cancelled || 0
      });
    }
    
    res.json({
      success: true,
      data: {
        overview: {
          total: overview?.total || 0,
          pending: overview?.pending || 0,
          confirmed: overview?.confirmed || 0,
          completed: overview?.completed || 0,
          cancelled: overview?.cancelled || 0,
          todayAppointments: todayStats?.todayAppointments || 0,
          upcomingAppointments: upcomingStats?.upcomingAppointments || 0
        },
        hospitalStats,
        dateStats
      }
    });
  } catch (error) {
    console.error("获取预约统计失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 删除预约（管理员权限）
router.delete("/admin/orders/:id", authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    
    // 查找并删除预约
    const appointment = await Appointment.findOneAndDelete({ appointmentId: id });
    if (!appointment) {
      return res.status(404).json({
        success: false,
        message: "预约不存在"
      });
    }
    
    console.log(`预约已删除: ${id}`);
    
    // 转换为响应格式
    const appointmentData = {
      id: appointment.appointmentId,
      userId: appointment.userId,
      hospitalId: appointment.hospitalId,
      hospitalName: appointment.hospitalName,
      departmentId: appointment.departmentId,
      departmentName: appointment.departmentName,
      doctorId: appointment.doctorId,
      doctorName: appointment.doctorName,
      appointmentDate: appointment.appointmentDate,
      timeSlot: appointment.timeSlot,
      status: appointment.status,
      price: appointment.price,
      queueNumber: appointment.queueNumber,
      createTime: appointment.createdAt.toISOString(),
      patientInfo: appointment.patientInfo,
      remark: appointment.remark
    };
    
    res.json({
      success: true,
      message: "预约已删除",
      data: appointmentData
    });
  } catch (error) {
    console.error("删除预约失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

export default router;